package com.learn.controllers;

import com.learn.entity.AdminEntity;
import com.learn.entity.AjaxResponse;
import com.learn.entity.RoleEntity;
import com.learn.form.AdminForm;
import com.learn.framework.util.DateUtil;
import com.learn.framework.util.FormValidateUtil;
import com.learn.framework.util.HttpRequestUtil;
import com.learn.framework.util.StringUtil;
import com.learn.repository.AdminRepository;
import com.learn.repository.RoleRepository;
import com.learn.service.AdminService;
import com.learn.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.Page;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private DateUtil dateUtil;
    @RequestMapping(value = "/login")
    public String loginAction(String userName, String password){
        return "admin/login";
    }

    @RequestMapping({"/list"})
    public String indexAction(Model model, @RequestParam(value = "page",defaultValue = "1") Integer page,
                              HttpServletRequest request){
        Page<AdminEntity> adminEntityPage =   adminService.getUserList(page - 1);
        model.addAttribute("totals", adminEntityPage.getTotalElements());
        model.addAttribute("totalPage", adminEntityPage.getTotalPages());
        model.addAttribute("page", adminEntityPage.getNumber()+1);
        model.addAttribute("datas", adminEntityPage);
        if(HttpRequestUtil.isAjax(request)){
            model.addAttribute("isAjax", true);
        }
        return "admin/list";
    }
    @RequestMapping("/view")
    public String viewAction(@RequestParam(value = "id", defaultValue = "0") Integer id, Model model){
        AdminEntity adminEntity         =   adminRepository.findById(id);
        List<RoleEntity> roleEntityList =   roleService.roleEntityList(adminEntity.getRoleId());

        model.addAttribute("admin", adminEntity);
        model.addAttribute("roles", roleEntityList);
        return "admin/view";
    }

    @GetMapping("/edit")
    public String editAction(Model model, HttpServletRequest request,
                             @RequestParam(value = "id", defaultValue = "0") Integer id){
        AdminEntity adminEntity = adminRepository.findById(id);
        if(adminEntity != null){
            List<RoleEntity> roleEntityList =   roleRepository.findAll();

            model.addAttribute("admin", adminEntity);
            model.addAttribute("roleList", roleEntityList);
        }
        return "admin/edit";
    }

    @GetMapping("/new")
    public String addAction(Model model){
        List<RoleEntity> roleEntityList =   roleRepository.findAll();
        model.addAttribute("roleList", roleEntityList);
        return "admin/new";
    }

    @PostMapping("/new")
    @ResponseBody
    public AjaxResponse addAction(@Valid AdminForm adminForm, BindingResult result) throws BindException{
        FormValidateUtil.validateForm(result);
        AjaxResponse response   =   new AjaxResponse();
        if(adminForm.getPassword().isEmpty()){
            response.setMessage("密码不能为空！");
        }else if(!adminForm.getPassword().equals(adminForm.getConfirmPassword())){
            response.setMessage("两次密码不一致！");
        }else{
            AdminEntity adminEntity =   new AdminEntity();
            String token    =   StringUtil.getRandomString(6);
            String password = adminForm.getPassword()+token;
            String md5Password  =   DigestUtils.md5DigestAsHex((password+token).getBytes());
            adminEntity.setPassword(md5Password);
            adminEntity.setName(adminForm.getName());
            adminEntity.setUpdateTime(DateUtil.getTime());
            adminEntity.setRoleId(adminForm.getRoleId());
            adminEntity.setCreateTime(DateUtil.getLongTime());
            adminEntity.setRealName(adminForm.getRealName());
            adminEntity.setStatus(adminForm.getStatus());
            adminEntity.setToken(token);

            adminRepository.save(adminEntity);
            response.setMessage("创建管理员成功！");
            response.setStatus(true);
            response.setReloadUrl("/admin/list");
        }

        return response;
    }

    @PostMapping("/edit")
    public @ResponseBody AjaxResponse editAction(@Valid AdminForm adminForm, BindingResult result) throws BindException{
        FormValidateUtil.validateForm(result);
        AjaxResponse response   =   new AjaxResponse();
        System.out.println(adminForm.toString());

        AdminEntity adminEntity =   adminRepository.findById(adminForm.getId());
        if(adminEntity != null){
            if(adminForm.getPassword() != null && adminForm.getPassword() != ""){
                if(adminForm.getPassword().equals(adminForm.getConfirmPassword())){
                    String token    =   adminEntity.getToken();
                    String password = adminForm.getPassword()+token;
                    String md5Password  =   DigestUtils.md5DigestAsHex((password+token).getBytes());
                    adminEntity.setPassword(md5Password);
                }else {
                    response.setStatus(false);
                    response.setMessage("两次输入密码不一致");
                    return response;
                }
            }
            adminEntity.setName(adminForm.getName());
            adminEntity.setRealName(adminForm.getRealName());
            adminEntity.setRoleId(adminForm.getRoleId());
            adminEntity.setUpdateTime(dateUtil.getTime());
            adminEntity.setStatus(adminForm.getStatus());
            adminRepository.save(adminEntity);
        }else{
            response.setStatus(true);
        }

        response.setStatus(true);
        response.setMessage("管理员修改成功");
        response.setReloadUrl("/admin/list");
        return response;
    }

    @RequestMapping("/delete/{id}/{page}")
    public @ResponseBody AjaxResponse deleteAction(@PathVariable Integer id, @PathVariable Integer page){
        System.out.println(id);
        AjaxResponse response   =   new AjaxResponse();
        if(!adminRepository.exists(id)){
            response.setMessage("找不到管理员！");
        }else{
            adminRepository.delete(id);
            response.setStatus(true);
            response.setMessage("删除管理员成功！");
            response.setReloadUrl("/admin/list?page=" + page);
        }
        return response;
    }
}
